package com.adcc.automation;

import com.adcc.automation.config.YmlConfig;
import com.adcc.automation.gui.Controller.AppController;
import com.adcc.automation.gui.Controller.UpdateController;
import com.jfoenix.controls.JFXDecorator;
import com.jfoenix.svg.SVGGlyphLoader;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowException;
import io.datafx.controller.flow.container.AnimatedFlowContainer;
import io.datafx.controller.flow.container.ContainerAnimations;
import io.datafx.controller.flow.context.FXMLViewFlowContext;
import io.datafx.controller.flow.context.ViewFlowContext;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;


public class App extends Application {
    
    private static final Logger logger = LoggerFactory.getLogger(App.class);
    
    @FXMLViewFlowContext
    private ViewFlowContext flowContext;
    
    private boolean updateLock;
    
    private Thread thread;
    
    public static void main(String[] args) {
        launch();
    }
    
    private void initView(Stage stage) throws IOException, FlowException {
        this.getClass().getResource("/fxml/app.fxml");
        //加载全局资源
        SVGGlyphLoader.loadGlyphsFont(App.class.getResourceAsStream("/fonts/icon.svg"), "icon.svg");
        Font.loadFont(getClass().getResourceAsStream("/fonts/msyh.ttf"), 16);
        //注册主页
        Flow flow = new Flow(AppController.class);
        AnimatedFlowContainer container = new AnimatedFlowContainer(Duration.millis(0), ContainerAnimations.SWIPE_LEFT);
        flowContext = new ViewFlowContext();
        flowContext.register("stage", stage);
        flow.createHandler(flowContext).start(container);
        JFXDecorator decorator = new JFXDecorator(stage, container.getView(), false, false, false);
        //最大化窗口
        decorator.setMaximized(false);
        //自定义标题
        Image image = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/icons/toolBlue.png")));
        ImageView imageView = new ImageView(image);
        imageView.setFitWidth(25);
        imageView.setFitHeight(25);
        Text text = new Text("自动化模拟工具（仅供测试）");
        text.setFill(Color.WHITE);
        text.setFont(Font.font("微软雅黑", 16));
        text.setTranslateY(5);
        text.setTranslateX(10);
        HBox hbox = gethBox(imageView, text, container);
        decorator.setGraphic(hbox);
        
        //将ui 容器绑定到舞台
        Scene scene = new Scene(decorator);
        scene.setFill(Color.TRANSPARENT);
        stage.setScene(scene);
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setResizable(false);
        //加入图标
        URL url = getClass().getClassLoader().getResource("icons/toolBlue.png");
        if (url != null) {
            stage.getIcons().add(new Image(url.toExternalForm()));
        }
        //绑定退出按钮
        decorator.setOnCloseButtonAction(() -> {
            AppController appController = (AppController) flowContext.getRegisteredObject("appView");
            appController.close();
        });
        //加载css 文件
        final ObservableList<String> stylesheets = scene.getStylesheets();
        stylesheets.addAll(Objects.requireNonNull(App.class.getResource("/css/jfoenix-components.css")).toExternalForm());
        //显示
        stage.show();
        logger.info("automation Tools client started successfully !");
    }
    // 自定义标题栏
    private HBox gethBox(ImageView imageView, Text text, AnimatedFlowContainer container) {
        HBox hbox = new HBox(imageView, text);
        hbox.setCursor(Cursor.HAND);
        // 为 ImageView 添加点击事件
        hbox.setOnMouseClicked(event -> {
            if(updateLock){
                Stage updateStage = (Stage) flowContext.getRegisteredObject("updateStage");
                updateStage.setIconified(false);
                updateStage.toFront();
                return;
            }
            Stage updateStage = new Stage();
            updateStage.setResizable(false);
            flowContext.register("updateStage", updateStage);
            Flow flowUpdate = new Flow(UpdateController.class);
            AnimatedFlowContainer containerUpdate = new AnimatedFlowContainer(Duration.millis(320), ContainerAnimations.FADE);
            try {
                flowUpdate.createHandler(flowContext).start(containerUpdate);
            } catch (FlowException e) {
                logger.info("open update window failed!");
            }
            JFXDecorator decoratorUpdate = new JFXDecorator(updateStage, containerUpdate.getView(), false, false, true);
            decoratorUpdate.setCustomMaximize(true);
            decoratorUpdate.getStyleClass().add("my_decorator");
            updateStage.setTitle("版本记录");
            Scene scene = new Scene(decoratorUpdate);
            scene.setFill(Color.TRANSPARENT);//设置舞台颜色透明
            
            final ObservableList<String> stylesheets = scene.getStylesheets();
            stylesheets.addAll(
                    Objects.requireNonNull(App.class.getResource("/css/jfoenix-components.css")).toExternalForm());
            updateStage.setScene(scene);
            updateStage.setResizable(false);
            updateStage.initStyle(StageStyle.TRANSPARENT);//设置窗口颜色透明
            updateStage.initModality(Modality.NONE);
            updateLock = true;
            updateStage.show();
            //窗口关闭监听
            updateStage.setOnCloseRequest(windowEvent -> updateLock = false);
        });
        return hbox;
    }
    
    @Override
    public void start(Stage stage) throws IOException, FlowException {
        initView(stage);
        intBackend();
    }
    
    private void intBackend() {
        thread = new Thread(() -> {
            YmlConfig.getInstance().init();
        });
        thread.start();
    }
}